package com.brian.hystrix.hystrix;

import com.brian.hystrix.service.OrderService;
import com.netflix.hystrix.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-25 09
 **/
public class OrderHystrixCommand extends HystrixCommand<Map<String,String>> {


    @Autowired
    private OrderService orderService;


    public OrderHystrixCommand(OrderService orderService) {
        super(setter());
        this.orderService = orderService;
    }

    @Override
    protected Map<String, String> run() throws Exception {
        System.out.println(Thread.currentThread().getName()+ "hystrix -- orderIndex");
        return orderService.orderIndex();
    }

    /**
     * 配置服务隔离机制
     * @return
     */
    private static Setter setter() {
        // 服务分组
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("order");
        // 服务标识
        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("order");
        // 线程池名称
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("order-pool");
        // 线程池配置 线程池大小为10,线程存活时间15秒 队列等待的阈值为100,超过100执行拒绝策略
        HystrixThreadPoolProperties.Setter threadPoolProperties = HystrixThreadPoolProperties.Setter().withCoreSize(10)
                .withKeepAliveTimeMinutes(15).withQueueSizeRejectionThreshold(100);
        // 命令属性配置Hystrix 开启超时
        HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter()
                // 采用线程池方式实现服务隔离
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                // 禁止
                .withExecutionTimeoutEnabled(false);
        return HystrixCommand.Setter.withGroupKey(groupKey).andCommandKey(commandKey).andThreadPoolKey(threadPoolKey)
                .andThreadPoolPropertiesDefaults(threadPoolProperties).andCommandPropertiesDefaults(commandProperties);

    }


    /**
     * 服务降级
     * @return
     */
    @Override
    protected Map<String, String> getFallback() {

        // 如果Hystrix发生熔断，当前服务不可用,直接执行Fallback方法
        System.out.println(Thread.currentThread().getName()+ "system error!");
        Map<String, String> map = new HashMap<>();
        map.put("code","500");
        map.put("message","服务器出了点问题！");
        return map;
    }
}
